import { login, getUserInfo, userPerm } from '@/api/user'
import { setToken, removeToken, getToken } from '@/utils/auth'
export default {
  namespaced: true,
  state: {
    // 用户信息
    userInfo: {},
    token: getToken(),
    userPerm: {},
    avatar: null,
    name: null
  },
  mutations: {
    // 设置保存token
    setToken(state, data) {
      state.token = data
      // 调用cookie方法保存数据做数据持久化
      setToken(data)
    },
    // 删除token
    removeToken(state) {
      state.token = null
      removeToken()
    },
    // 保存用户数据
    setuserinfo(state, data) {
      state.userInfo = data
      state.avatar = data.image
      state.name = data.username
    },
    // 删除用户信息
    removeuserinfo(state) {
      state.userInfo = {}
    },
    // 保存用户权限
    setuserperm(state, data) {
      state.userPerm = data
    },
    // 删除用户权限
    removeuserperm(state) {
      state.userPerm = {}
    }
  },
  actions: {
    // 调用接口登录
    async login(context, data) {
      const res = await login(data)
      context.commit('setToken', res.jwt)
    },
    // 调用接口获取用户信息
    async getuserinfo(context) {
      // 获取用户信息
      const res = await getUserInfo()
      context.commit('setuserinfo', res)
      // 获取用户权限
      const result = await userPerm()
      context.commit('setuserperm', result)
    },
    logout(store) {
      store.commit('removeToken')
      store.commit('removeuserinfo')
      store.commit('removeuserperm')
    }
  }
}

